package kr.hkit.androidcomplete01.ch19;

import kr.hkit.androidcomplete01.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.HandlerThread;
import android.view.View;
import android.widget.TextView;

public class BackWork3 extends Activity {

	TextView mResult;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch19_backwork);
		mResult = (TextView) findViewById(R.id.result);
	}

	public void mOnClick(View v) {
		int start = 0, end = 100;
		int result;
		WaitDlg dlg = new WaitDlg(BackWork3.this, "WaitTest", "Now calculating");
		dlg.start();
		result = Accumulate(start, end);
		mResult.setText("" + result);
		WaitDlg.stop(dlg);
	}

	int Accumulate(int start, int end) {
		int sum = 0;
		for (int i = start; i <= end; i++) {
			sum += i;
			try {
				Thread.sleep(20);
			} catch (InterruptedException e) {
				;
			}
		}
		return sum;
	}

	static class WaitDlg extends HandlerThread {// * HendlerThread로부터 상속
		Context mContext;
		String mTitle;
		String mMsg;
		ProgressDialog mProgress;

		WaitDlg(Context context, String title, String msg) {
			super("waitdlg");
			mContext = context;
			mTitle = title;
			mMsg = msg;
			setDaemon(true);
		}

		protected void onLooperPrepared() {
			mProgress = new ProgressDialog(mContext);
			mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			mProgress.setTitle(mTitle);
			mProgress.setMessage(mMsg);
			mProgress.setCancelable(false);
			mProgress.show();
		}

		static void stop(WaitDlg dlg) {// 스레드 외부에서 종료를 위해 호출된다.
			dlg.mProgress.dismiss();
			// 대화상자가 사라지기 전까지 대기해 줘야 함, 메시지 루프 종료해야 함
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				;
			}
			dlg.getLooper().quit();
		}
	}
}
